package top.mcwebsite.playandroid.common.uiWidget

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.dp
import top.mcwebsite.playandroid.common.network.*


data class ErrorModel(
    val apiException: ApiException = NetworkApiException.unknown(),
    val retry: () -> Unit
)

@Composable
fun ErrorPage(
    modifier: Modifier = Modifier,
    errorModel: ErrorModel
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = modifier.fillMaxSize()
    ) {
        ErrorContent(errorModel)
    }
}

@Composable
fun ErrorContent(
    errorModel: ErrorModel,
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = rememberVectorPainter(image = errorModel.apiException.getIconWithApiException()),
            contentDescription = null,
            modifier = Modifier.size(100.dp)
        )
        Text(errorModel.apiException.errorMsg)
        Button(onClick = {
            errorModel.retry.invoke()
        }) {
            Text("重试")
        }
    }
}

private fun ApiException.getIconWithApiException(): ImageVector =
    when (this.errorCode) {
        NetworkApiException.NoInternet -> Icons.Outlined.WifiOff
        else -> Icons.Outlined.ErrorOutline
    }